﻿using System;
using System.Windows.Forms;
using System.Linq;
using System.Collections.Generic;
using System.Threading;
using System.Drawing;
using System.Net;
using System.IO;

namespace HRN.Bot {
    public partial class MainMenu {
        #region Variable
        internal int WaitingAmount = 0;
        internal List<UrlHistory> urlhistory = new List<UrlHistory>();
        internal Random randm = new Random();
        internal BrowserWeb browserWeb = new BrowserWeb();
        #endregion
        internal MainMenu() {
            InitializeComponent();
        }

        private object Start() {
            int number;
            if (ListBoxURL.Items.Count > 0)
                if (listBoxProxy.Items.Count > 0)
                    if (Int32.TryParse(textBoxRequestCounter.Text, out number))
                        if (Int32.TryParse(textBoxClickWait.Text, out number)) {
                            ListBoxURL.SelectedIndex = 0;
                            browserWeb.Start();
                        } else
                            InfostoolStripStatusLabel.Text = "Click Wait Not Number!";
                    else
                        InfostoolStripStatusLabel.Text = "Request Counter not Number!";
                else
                    InfostoolStripStatusLabel.Text = "Proxy Not Found!";
            else
                InfostoolStripStatusLabel.Text = "Url No Found!";
            return null;
        }
        internal void navigate(string url) {
            try {
                WebBrowser1.Navigate(url);
                InfostoolStripStatusLabel.Text = "Navigating browser...";
                GroupBox3.Text = "Browser - Url : " + ListBoxURL.SelectedItem.ToString() + " - Proxy : " + listBoxProxy.SelectedItem.ToString();
                browserWeb.Wait(WaitingAmount = randm.Next(10, Convert.ToInt32(textBoxDelay.Text)));
                StartWait(15);
                
                browserWeb.ClickSkipButton();
            } catch (Exception ex) {
                InfostoolStripStatusLabel.Text = "Dont Navigated Browser!" + ex.Message + " " + ex.InnerException;
                listBoxProxy.Items.Remove(listBoxProxy.SelectedIndex);
                browserWeb.Wait(1);
            }
        }
        public void StartWait(int wait) {
            WaitCountertoolStripStatusLabel4.Text = wait.ToString();
            WaitCounter.Start();
        }
        internal void AddHistory() {
            urlhistory[ListBoxURL.SelectedIndex].Add(listBoxProxy.SelectedItem.ToString());
        }
        private void Wait_tick(object sender, System.EventArgs e) {
            WaitCountertoolStripStatusLabel4.Text = (Convert.ToInt32(WaitCountertoolStripStatusLabel4.Text) - 1).ToString();
            Application.DoEvents();
            if (Convert.ToInt32(WaitCountertoolStripStatusLabel4.Text) <= 0) {
                WaitCounter.Stop();
                //WaitCountertoolStripStatusLabel4.Text = 0.ToString();
            }
        }

        private void Form1_Load(object sender, System.EventArgs e) {
            TestDataLoad();
        }
        private void TestDataLoad() {
            if (Convert.ToInt32(textBoxRequestCounter.Text) == 2) {
                string desktoppath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
                string[] lstring;
                if (System.IO.File.Exists(desktoppath + "\\proxy.txt")) {
                    lstring = File.ReadAllLines(desktoppath + "\\proxy.txt", System.Text.Encoding.Default);
                    LoadProxy(lstring,true);
                }
                if (System.IO.File.Exists(desktoppath + "\\url.txt")) {
                    lstring = File.ReadAllLines(desktoppath + "\\url.txt", System.Text.Encoding.Default);
                    LoadUrl(lstring,true);
                }
            }
        }
        private static MainMenu _DefaultInstance;
        public static MainMenu DefaultInstance {
            get {
                if (_DefaultInstance == null)
                    _DefaultInstance = new MainMenu();

                return _DefaultInstance;
            }
        }
        public void LoadUrl(string[] lstring,bool IsClear) {
            if (IsClear)
                ListBoxURL.Items.Clear();
            ListBoxURL.Items.AddRange(lstring);
            for (int i = 0; i < ListBoxURL.Items.Count; i++)
                if (ListBoxURL.Items[i].ToString() == " " || ListBoxURL.Items[i].ToString() == "" || string.IsNullOrEmpty(ListBoxURL.Items[i].ToString()))
                    ListBoxURL.Items.RemoveAt(i);
            if (ListBoxURL.Items[ListBoxURL.Items.Count - 1].ToString() == "")
                ListBoxURL.Items.RemoveAt(ListBoxURL.Items.Count - 1);
            for (int i = 0; i < ListBoxURL.Items.Count; i++) {
                bool count = false;
                foreach (UrlHistory item in urlhistory)
                    if (item.Url == ListBoxURL.Items[i].ToString())
                        count = true;
                if (!count) {
                    UrlHistory history = new UrlHistory();
                    history.Url = ListBoxURL.Items[i].ToString();
                    urlhistory.Add(history);
                }
            }
            GroupBoxURL.Text = "URL : " + ListBoxURL.Items.Count;
        }
        public void LoadProxy(string[] lstring,bool IsClear) {
            if (IsClear)
                listBoxProxy.Items.Clear();
            listBoxProxy.Items.AddRange(lstring);
            for (int i = 0; i < listBoxProxy.Items.Count; i++)
                if (string.IsNullOrEmpty((string)listBoxProxy.Items[i]))
                    listBoxProxy.Items.RemoveAt(i);
            if (listBoxProxy.Items[listBoxProxy.Items.Count - 1].ToString() == "")
                listBoxProxy.Items.RemoveAt(listBoxProxy.Items.Count - 1);
            GroupBoxProxy.Text = "Proxy : " + listBoxProxy.Items.Count;
        }
        public void LoadFromText(string title) {
            OpenFileDialog1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
            OpenFileDialog1.Title = title;
            if (OpenFileDialog1.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) {
                string[] lstring = File.ReadAllLines(OpenFileDialog1.FileName, System.Text.Encoding.Default);
                if (title == "PROXY")
                    LoadProxy(lstring,true);
                else if (title == "URL")
                    LoadUrl(lstring,true);
            }
        }

        private void textBoxRequestCounter_TextChanged(object sender, EventArgs e) {
            int number;
            if (!Int32.TryParse(textBoxRequestCounter.Text,out number)) {
                MessageBox.Show("Request Counter Type is Not Number");
                toolStripProgressBar1.Maximum = 100;
            } else
                toolStripProgressBar1.Maximum = Convert.ToInt32(textBoxRequestCounter.Text);
        }
        private void startToolStripMenuItemStart_Click(object sender, EventArgs e) {
            //(new Thread(new ThreadStart(SkipButtonClicked))).Start();
            Start();
            //backgroundWorker1.RunWorkerAsync();
        }
        private void restartToolStripMenuItemRestart_Click(object sender, EventArgs e) {
            HRNProxy.DisableProxy();
            Application.Restart();
        }
        private void disableProxyToolStripMenuItem_Click(object sender, EventArgs e) {
            HRNProxy.DisableProxy();
        }
        private void ProcessHistorytoolsToolStripMenuItem_Click(object sender, EventArgs e) {
            ProcessHistory processHistory = new ProcessHistory();
            processHistory.Show();
        }
        private void internetPropertiesToolStripMenuItem_Click(object sender, EventArgs e) {
            HRNProxy.OpenLanSettings();
        }
        private void loadUrlToolStripMenuItem_Click(object sender, EventArgs e) {
            LoadFromText("URL");
        }
        private void loadProxyToolStripMenuItem_Click(object sender, EventArgs e) {
            LoadFromText("PROXY");
        }
        private void WebBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {
            browserWeb.ClickAfterNavigated();
        }
        private void deleteSelectedLinkToolStripMenuItem_Click(object sender, EventArgs e) {
            ListBoxURL.Items.Remove(ListBoxURL.SelectedItem);
        }
        private void deleteSelectedProxyToolStripMenuItem_Click(object sender, EventArgs e) {
            listBoxProxy.Items.Remove(listBoxProxy.SelectedItem);
        }
        private void deleteAllToolStripMenuItem_Click(object sender, EventArgs e) {
            listBoxProxy.Items.Clear();
        }
        private void contextMenuStripProxy_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
            if (listBoxProxy.SelectedItem == null)
                deleteSelectedProxyToolStripMenuItem.Enabled = false;
            else
                deleteSelectedProxyToolStripMenuItem.Enabled = true;
        }
        private void deleteAllToolStripMenuItem1_Click(object sender, EventArgs e) {
            ListBoxURL.Items.Clear();
        }
        private void contextMenuStripURL_Opening(object sender, System.ComponentModel.CancelEventArgs e) {
            if (ListBoxURL.SelectedItem == null)
                deleteSelectedLinkToolStripMenuItem.Enabled = false;
            else
                deleteSelectedLinkToolStripMenuItem.Enabled = true;
        }
        private void WebBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e) {
            browserWeb.ClickAfterNavigated();
        }
        private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e) {
            e.Result = Start();
        }
        private void textBoxClickWait_TextChanged(object sender, EventArgs e) {
            int number;
            if (!Int32.TryParse(textBoxClickWait.Text, out number))
                MessageBox.Show(" Click Wait Type is Not Number");
        }
        private void addLinksToolStripMenuItem_Click(object sender, EventArgs e) {
            AddLinkOrProxy addLinkOrProxy = new AddLinkOrProxy();
            addLinkOrProxy.ShowDialog();
        }
        private void addProxysToolStripMenuItem_Click(object sender, EventArgs e) {
            AddLinkOrProxy addLinkOrProxy = new AddLinkOrProxy();
            addLinkOrProxy.ShowDialog();
        }
        private void textBoxDelay_TextChanged(object sender, EventArgs e) {
            int number;
            if (!Int32.TryParse(textBoxDelay.Text,out number))
                MessageBox.Show(" Delay Type is Not Number");
        }
        private void downloadProxyToolStripMenuItem_Click(object sender, EventArgs e) {
            string url=string.Empty;
            string xml = "";
            if (browserWeb.GetUrl(ref url, ref xml)) {
                string proxylist = browserWeb.ParseXml(ref xml);
                LoadProxy(proxylist.Split(Environment.NewLine.ToCharArray()), true);
                if (System.IO.File.Exists(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\proxy.txt")) {
                    File.WriteAllLines(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\proxy.txt", proxylist.Split(Environment.NewLine.ToCharArray()));
                }
                InfostoolStripStatusLabel.Text = "Proxy Downloaded. \nurl: " + url;
                MessageBox.Show("Proxy Downloaded. \nurl: " + url);
            }
        }
        private void stopToolStripMenuItem_Click(object sender, EventArgs e) {
            if (stopToolStripMenuItem.Text == "Stop") {
                stopToolStripMenuItem.Text = "Continue";
            } else {
                stopToolStripMenuItem.Text = "Stop";
            } while (stopToolStripMenuItem.Text == "Continue") {
                Application.DoEvents();
            }
        }
        private void WebBrowser1_Navigating(object sender, WebBrowserNavigatingEventArgs e) {
            //if (WebBrowser1.ReadyState != WebBrowserReadyState.Uninitialized)
            //    while (WebBrowser1.ReadyState == WebBrowserReadyState.Loading)
        }
        private void MainMenu_FormClosed(object sender, FormClosedEventArgs e) {
            HRNProxy.DisableProxy();
        }
    }
}